import React, { useEffect } from 'react';
import { connect } from 'dva';
import { history } from 'umi';
import { NoteState } from '@/models/note';
import HeadToolbar, { ToolbarButton } from '@/components/HeadToolbar';
import NoteList from '@/components/NoteList';
import {
  PlusOutlined,
  ReloadOutlined,
  LoadingOutlined,
} from '@ant-design/icons';

interface IndexPageProps extends NoteState {
  dispatch: Function;
}

const IndexPage: React.FC<IndexPageProps> = ({
  netStatus,
  loading,
  noteList,
  dispatch,
}) => {
  const newNote = () => {
    history.push('/note/new');
  };

  const handleCheckUpdate = () => {
    dispatch({ type: 'note/update' });
  };

  useEffect(() => {
    handleCheckUpdate();
  }, []);

  return (
    <div>
      <HeadToolbar>
        <ToolbarButton onClick={newNote} text="新建" icon={<PlusOutlined />} />
        {loading ? (
          <ToolbarButton text="加载中" icon={<LoadingOutlined />} />
        ) : (
          <ToolbarButton
            onClick={handleCheckUpdate}
            text={netStatus ? '刷新' : '网络错误'}
            icon={<ReloadOutlined />}
          />
        )}
      </HeadToolbar>
      <NoteList list={noteList} />
    </div>
  );
};

const mapStateToProps = ({ note }: { note: NoteState }) => {
  return { ...note };
};

export default connect(mapStateToProps)(IndexPage);
